import React, {useState, useRef, useEffect} from 'react';
import {View, TouchableOpacity} from 'react-native';
import {FlashList,FlashListRef} from '@shopify/flash-list';
import {useTranslation} from 'react-i18next';
import {selectCountries, setSelectedCountry} from '@/store/slices/countrySlice';
import {useDispatch, useSelector} from 'react-redux';
import storage from '@/utils/storage';
import {Search, Icon, Text, useAppTheme, TextInput} from 'tsun-smart-ui';

// 修改 groupByFirstLetter 函数，为每个项添加位置标识
function groupByFirstLetter(
  sorted: CountryItem[],
  t,
): (string | (CountryItem & {isFirst?: boolean; isLast?: boolean}))[] {
  // 排序按 lastName
  const result: (
    | string
    | (CountryItem & {isFirst?: boolean; isLast?: boolean})
  )[] = [];
  let currentLetter = '';
  let currentGroup: (CountryItem & {isFirst?: boolean; isLast?: boolean})[] =
    [];

  // 第一步：分组并标记 section header
  for (const item of sorted) {
    const firstLetter = item.type || t(item.code)[0].toUpperCase();
    if (firstLetter !== currentLetter) {
      // 处理上一组的最后一个元素
      if (currentGroup.length > 0) {
        currentGroup[currentGroup.length - 1].isLast = true;
        // 将处理好的组添加到结果中
        result.push(...currentGroup);
      }

      // 开始新的一组
      currentLetter = firstLetter;
      result.push(currentLetter); // 添加 section header
      currentGroup = [{...item, isFirst: true}];
    } else {
      currentGroup.push({...item});
    }
  }

  // 处理最后一组
  if (currentGroup.length > 0) {
    currentGroup[currentGroup.length - 1].isLast = true;
    result.push(...currentGroup);
  }

  return result;
}

// 修改 renderSectionHeader 函数，添加上边距

export type CountryItem = {
  code: string;
  value: string;
  zoneList: {
    code: string;
    value: string;
  }[];
  type?: string;
};

type AlphabetSection = {
  letter: string;
  countries: CountryItem[];
  index: number; // 用于定位
};

const CountryPicker = ({
  navigation,
  route: {params: {current} = {}},
}: ReactNavigation.RootStackScreenProps<'CountryPicker'>) => {
  const {t} = useTranslation();
  const theme = useAppTheme();
  const countries = useSelector(selectCountries);
  const dispatch = useDispatch();
  const [filteredCountries, setFilteredCountries] =
    useState<(CountryItem | string)[]>(countries);
  const [alphabetSections, setAlphabetSections] = useState<AlphabetSection[]>(
    [],
  );
  const [searchQuery, setSearchQuery] = useState('');
  const [activeLetter, setActiveLetter] = useState('');
  const flashListRef = useRef<FlashListRef<CountryItem | string>>(null);
  const sortedCountries = useRef<(CountryItem | string)[]>([]);
  const isChinese = storage.getString('language') === 'zh-CN';
  // 获取国家数据
  useEffect(() => {
    if (countries.length > 0) {
      if (isChinese) {
        const pinyin = require('tiny-pinyin');
        sortedCountries.current = countries
          .map(item => {
            const name = t(item.code);
            const type = pinyin.convertToPinyin(name[0])[0];
            return {
              type,
              ...item,
            };
          })
          .sort((a, b) => a.type.localeCompare(b.type));
      } else {
        sortedCountries.current = [...countries].sort((a, b) =>
          t(a.code).localeCompare(t(b.code)),
        );
      }
      generateAlphabetSections(sortedCountries.current!);
      sortedCountries.current = groupByFirstLetter(
        sortedCountries.current as CountryItem[],
        t,
      );
      setFilteredCountries(sortedCountries.current);
    }
  }, [countries]);

  // 生成字母索引分组
  const generateAlphabetSections = (data: (CountryItem | string)[]) => {
    const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    const sections: AlphabetSection[] = [];

    let currentIndex = 0;
    let headerCount = 0; // 用于跟踪已添加的 section header 数量

    alphabet.forEach(letter => {
      const countriesForLetter = data.filter(country => {
        if (typeof country === 'object') {
          if (country.type) {
            return country.type === letter;
          } else {
            return t(country.code).toUpperCase().startsWith(letter);
          }
        }
      });
      if (countriesForLetter.length > 0) {
        sections.push({
          letter,
          countries: countriesForLetter,
          index: currentIndex + headerCount, // 加上之前的 section header 数量
        });
        currentIndex += countriesForLetter.length;
        headerCount++; // 每添加一个字母分组，header 数量加 1
      }
    });
    setAlphabetSections(sections);
  };

  // 搜索处理
  const handleSearch = (query: string) => {
    setSearchQuery(query);
    if (!!query) {
      const filtered = sortedCountries.current.filter(country =>
        t(country.code).toLowerCase().includes(query.toLowerCase()),
      );
      setFilteredCountries(groupByFirstLetter(filtered, t));
    } else {
      setFilteredCountries(sortedCountries.current);
    }
  };

  // 点击字母快速跳转
  const scrollToLetter = (letter: string) => {
    const section = alphabetSections.find(s => s.letter === letter);
    if (section && flashListRef.current) {
      flashListRef.current.scrollToIndex({
        index: section.index,
        viewPosition: 0,
        animated: true,
      });
      setActiveLetter(letter);

      // 短暂高亮后恢复
      setTimeout(() => {
        setActiveLetter('');
      }, 1500);
    }
  };
  const renderCountryItem = ({
    item,
  }: {
    item: CountryItem & {isFirst?: boolean; isLast?: boolean};
  }) => {
    // 根据位置确定圆角样式
    let borderRadiusStyle = '';
    if (item.isFirst && item.isLast) {
      borderRadiusStyle = 'rounded-lg'; // 如果只有一个项目，四周都是圆角
    } else if (item.isFirst) {
      borderRadiusStyle = 'rounded-t-lg'; // 第一个项目，上方圆角
    } else if (item.isLast) {
      borderRadiusStyle = 'rounded-b-lg'; // 最后一个项目，下方圆角
    }

    return (
      <View
        className={`px-5 w-full ${borderRadiusStyle}`}
        style={{
          backgroundColor: theme.colors?.neutral?.white,
        }}>
        <TouchableOpacity
          style={{
            borderBottomWidth: item.isLast ? 0 : 1,

            borderBottomColor: theme.colors?.border?.primary,
          }}
          onPress={() => {
            dispatch(setSelectedCountry(item));
            navigation.goBack();
          }}>
          <Text className="py-[13.5]">{t(item.code)}</Text>
        </TouchableOpacity>
      </View>
    );
  };

  // 渲染国家项
  // 字母索引渲染
  const renderAlphabetSidebar = () => {
    return (
      <View className="absolute right-2 top-[40px] bottom-0 justify-center z-10 ">
        <View className="py-1 px-0.5 overflow-hidden">
          {alphabetSections.map(section => (
            <TouchableOpacity
              key={section.letter}
              onPress={() => scrollToLetter(section.letter)}
              className="py-0.5">
              <Text
                variant="caption"
                className="text-center w-6"
                style={{
                  color:
                    activeLetter === section.letter
                      ? theme.colors?.brand?.primary
                      : theme.colors?.neutral?.title,
                }}>
                {section.letter}
              </Text>
            </TouchableOpacity>
          ))}
        </View>
      </View>
    );
  };
  const renderSectionHeader = ({item}: {item: string}) => (
    <Text className="ml-5 mt-3 mb-1">{item}</Text>
  );
  return (
    <View className="flex-1 px-4 mt-3 relative">
      {/* 搜索栏 */}
      <View>
        <Search
          placeholder={t('pb.search.countries/regions', {
            defaultValue: '搜索国家/地区',
          })}
          value={searchQuery}
          onChangeText={handleSearch}
          cancelText={t('user.logOutCancel', {defaultValue: '取消'})}
        />
      </View>
      {/* {current && (
        <View className="mt-5">
          <Text className=" mb-2">
            {t('common.currentTip')}
          </Text>

          <View className="flex-row flex-between  px-5 py-3 rounded-lg">
            <Text>{current}</Text>
            <Icon
              name="check"
              size={20}
              color={theme.colors?.brand?.primary}></Icon>
          </View>
        </View>
      )} */}
      {current && (
        <TextInput
          className=" mt-5"
          inputWrapperStyle={{
            borderRadius: 8,
          }}
          value={current}
          label={t('common.currentTip')}
          right={
            <Icon
              name="check"
              size={20}
              color={theme.colors?.brand?.primary}></Icon>
          }></TextInput>
      )}
      {renderAlphabetSidebar()}

      <View className="flex-1 mt-3">
        <FlashList
          ref={flashListRef}
          data={filteredCountries}
          showsVerticalScrollIndicator={false}
          keyboardShouldPersistTaps="handled"
          contentContainerStyle={{paddingBottom: 40}}
          ListEmptyComponent={
            <View className="flex-1 justify-center items-center p-8">
              <Text style={{color: theme.colors?.neutral?.title}}>
                {t('country.noResults', {
                  defaultValue: '未找到匹配的国家/地区',
                })}
              </Text>
            </View>
          }
          renderItem={({item}) => {
            if (typeof item === 'string') {
              // Rendering header
              return renderSectionHeader({item});
            } else {
              // Render item
              return renderCountryItem({item});
            }
          }}
          getItemType={item => {
            // To achieve better performance, specify the type based on the item
            if (typeof item === 'string') {
              return 'sectionHeader';
            } else {
              return 'row';
            }
          }}
        />
      </View>
    </View>
  );
};

export default CountryPicker;
